home *** CD-ROM | disk | FTP | other *** search
/ Turnbull China Bikeride / Turnbull China Bikeride - Disc 2.iso / STUTTGART / UTIL / PROGRAMMING / ZIPLIB / c / deflate < prev    next >
Text File  |  1996-07-31  |  43KB  |  1,181 lines

  1. /* deflate.c -- compress data using the deflation algorithm
  2.  * Copyright (C) 1995-1996 Jean-loup Gailly.
  3.  * For conditions of distribution and use, see copyright notice in zlib.h 
  4.  */
  5.  
  6. /*
  7.  *  ALGORITHM
  8.  *
  9.  *      The "deflation" process depends on being able to identify portions
  10.  *      of the input text which are identical to earlier input (within a
  11.  *      sliding window trailing behind the input currently being processed).
  12.  *
  13.  *      The most straightforward technique turns out to be the fastest for
  14.  *      most input files: try all possible matches and select the longest.
  15.  *      The key feature of this algorithm is that insertions into the string
  16.  *      dictionary are very simple and thus fast, and deletions are avoided
  17.  *      completely. Insertions are performed at each input character, whereas
  18.  *      string matches are performed only when the previous match ends. So it
  19.  *      is preferable to spend more time in matches to allow very fast string
  20.  *      insertions and avoid deletions. The matching algorithm for small
  21.  *      strings is inspired from that of Rabin & Karp. A brute force approach
  22.  *      is used to find longer strings when a small match has been found.
  23.  *      A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  24.  *      (by Leonid Broukhis).
  25.  *         A previous version of this file used a more sophisticated algorithm
  26.  *      (by Fiala and Greene) which is guaranteed to run in linear amortized
  27.  *      time, but has a larger average cost, uses more memory and is patented.
  28.  *      However the F&G algorithm may be faster for some highly redundant
  29.  *      files if the parameter max_chain_length (described below) is too large.
  30.  *
  31.  *  ACKNOWLEDGEMENTS
  32.  *
  33.  *      The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  34.  *      I found it in 'freeze' written by Leonid Broukhis.
  35.  *      Thanks to many people for bug reports and testing.
  36.  *
  37.  *  REFERENCES
  38.  *
  39.  *      Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  40.  *      Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  41.  *
  42.  *      A description of the Rabin and Karp algorithm is given in the book
  43.  *         "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  44.  *
  45.  *      Fiala,E.R., and Greene,D.H.
  46.  *         Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  47.  *
  48.  */
  49.  
  50. /* $Id: deflate.c,v 1.13 1996/05/22 11:52:21 me Exp $ */
  51.  
  52. #include "deflate.h"
  53.  
  54. char deflate_copyright[] = " deflate 1.0.2 Copyright 1995-1996 Jean-loup Gailly ";
  55. /*
  56.   If you use the zlib library in a product, an acknowledgment is welcome
  57.   in the documentation of your product. If for some reason you cannot
  58.   include such an acknowledgment, I would appreciate that you keep this
  59.   copyright string in the executable of your product.
  60.  */
  61.  
  62. /* ===========================================================================
  63.  *  Function prototypes.
  64.  */
  65. local void fill_window    OF((deflate_state *s));
  66. local int  deflate_stored OF((deflate_state *s, int flush));
  67. local int  deflate_fast   OF((deflate_state *s, int flush));
  68. local int  deflate_slow   OF((deflate_state *s, int flush));
  69. local void lm_init        OF((deflate_state *s));
  70. local uInt longest_match  OF((deflate_state *s, IPos cur_match));
  71. local void putShortMSB    OF((deflate_state *s, uInt b));
  72. local void flush_pending  OF((z_stream *strm));
  73. local int read_buf        OF((z_stream *strm, charf *buf, unsigned size));
  74. #ifdef ASMV
  75.       void match_init OF((void)); /* asm code initialization */
  76. #endif
  77.  
  78. #ifdef DEBUG
  79. local  void check_match OF((deflate_state *s, IPos start, IPos match,
  80.                             int length));
  81. #endif
  82.  
  83. /* ===========================================================================
  84.  * Local data
  85.  */
  86.  
  87. #define NIL 0
  88. /* Tail of hash chains */
  89.  
  90. #ifndef TOO_FAR
  91. #  define TOO_FAR 4096
  92. #endif
  93. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  94.  
  95. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  96. /* Minimum amount of lookahead, except at the end of the input file.
  97.  * See deflate.c for comments about the MIN_MATCH+1.
  98.  */
  99.  
  100. typedef int (*compress_func) OF((deflate_state *s, int flush));
  101. /* Compressing function */
  102.  
  103. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  104.  * the desired pack level (0..9). The values given below have been tuned to
  105.  * exclude worst case performance for pathological files. Better values may be
  106.  * found for specific files.
  107.  */
  108. typedef struct config_s {
  109.    ush good_length; /* reduce lazy search above this match length */
  110.    ush max_lazy;    /* do not perform lazy search above this match length */
  111.    ush nice_length; /* quit search above this match length */
  112.    ush max_chain;
  113.    compress_func func;
  114. } config;
  115.  
  116. local config configuration_table[10] = {
  117. /*      good lazy nice chain */
  118. /* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
  119. /* 1 */ {4,    4,  8,    4, deflate_fast}, /* maximum speed, no lazy matches */
  120. /* 2 */ {4,    5, 16,    8, deflate_fast},
  121. /* 3 */ {4,    6, 32,   32, deflate_fast},
  122.  
  123. /* 4 */ {4,    4, 16,   16, deflate_slow},  /* lazy matches */
  124. /* 5 */ {8,   16, 32,   32, deflate_slow},
  125. /* 6 */ {8,   16, 128, 128, deflate_slow},
  126. /* 7 */ {8,   32, 128, 256, deflate_slow},
  127. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  128. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* maximum compression */
  129.  
  130. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  131.  * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  132.  * meaning.
  133.  */
  134.  
  135. #define EQUAL 0
  136. /* result of memcmp for equal strings */
  137.  
  138. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  139.  
  140. /* ===========================================================================
  141.  * Update a hash value with the given input byte
  142.  * IN  assertion: all calls to to UPDATE_HASH are made with consecutive
  143.  *    input characters, so that a running hash key can be computed from the
  144.  *    previous key instead of complete recalculation each time.
  145.  */
  146. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  147.  
  148.  
  149. /* ===========================================================================
  150.  * Insert string str in the dictionary and set match_head to the previous head
  151.  * of the hash chain (the most recent string with same hash key). Return
  152.  * the previous length of the hash chain.
  153.  * IN  assertion: all calls to to INSERT_STRING are made with consecutive
  154.  *    input characters and the first MIN_MATCH bytes of str are valid
  155.  *    (except for the last MIN_MATCH-1 bytes of the input file).
  156.  */
  157. #define INSERT_STRING(s, str, match_head) \
  158.    (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  159.     s->prev[(str) & s->w_mask] = match_head = s->head[s->ins_h], \
  160.     s->head[s->ins_h] = (Pos)(str))
  161.  
  162. /* ===========================================================================
  163.  * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  164.  * prev[] will be initialized on the fly.
  165.  */
  166. #define CLEAR_HASH(s) \
  167.     s->head[s->hash_size-1] = NIL; \
  168.     zmemzero((charf *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  169.  
  170. /* ========================================================================= */
  171. int deflateInit_(strm, level, version, stream_size)
  172.     z_stream *strm;
  173.     int level;
  174.     const char *version;
  175.     int stream_size;
  176. {
  177.     return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  178.              Z_DEFAULT_STRATEGY, version, stream_size);
  179.     /* To do: ignore strm->next_in if we use it as window */
  180. }
  181.  
  182. /* ========================================================================= */
  183. int deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
  184.           version, stream_size)
  185.     z_stream *strm;
  186.     int  level;
  187.     int  method;
  188.     int  windowBits;
  189.     int  memLevel;
  190.     int  strategy;
  191.     const char *version;
  192.     int stream_size;
  193. {
  194.     deflate_state *s;
  195.     int noheader = 0;
  196.  
  197.     ushf *overlay;
  198.     /* We overlay pending_buf and d_buf+l_buf. This works since the average
  199.      * output size for (length,distance) codes is <= 24 bits.
  200.      */
  201.  
  202.     if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  203.         stream_size != sizeof(z_stream)) {
  204.     return Z_VERSION_ERROR;
  205.     }
  206.     if (strm == Z_NULL) return Z_STREAM_ERROR;
  207.  
  208.     strm->msg = Z_NULL;
  209.     if (strm->zalloc == Z_NULL) {
  210.     strm->zalloc = zcalloc;
  211.     strm->opaque = (voidpf)0;
  212.     }
  213.     if (strm->zfree == Z_NULL) strm->zfree = zcfree;
  214.  
  215.     if (level == Z_DEFAULT_COMPRESSION) level = 6;
  216.  
  217.     if (windowBits < 0) { /* undocumented feature: suppress zlib header */
  218.         noheader = 1;
  219.         windowBits = -windowBits;
  220.     }
  221.     if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  222.         windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  223.     strategy < 0 || strategy > Z_HUFFMAN_ONLY) {
  224.         return Z_STREAM_ERROR;
  225.     }
  226.     s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  227.     if (s == Z_NULL) return Z_MEM_ERROR;
  228.     strm->state = (struct internal_state FAR *)s;
  229.     s->strm = strm;
  230.  
  231.     s->noheader = noheader;
  232.     s->w_bits = windowBits;
  233.     s->w_size = 1 << s->w_bits;
  234.     s->w_mask = s->w_size - 1;
  235.  
  236.     s->hash_bits = memLevel + 7;
  237.     s->hash_size = 1 << s->hash_bits;
  238.     s->hash_mask = s->hash_size - 1;
  239.     s->hash_shift =  ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  240.  
  241.     s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  242.     s->prev   = (Posf *)  ZALLOC(strm, s->w_size, sizeof(Pos));
  243.     s->head   = (Posf *)  ZALLOC(strm, s->hash_size, sizeof(Pos));
  244.  
  245.     s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  246.  
  247.     overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  248.     s->pending_buf = (uchf *) overlay;
  249.  
  250.     if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  251.         s->pending_buf == Z_NULL) {
  252.         strm->msg = ERR_MSG(Z_MEM_ERROR);
  253.         deflateEnd (strm);
  254.         return Z_MEM_ERROR;
  255.     }
  256.     s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  257.     s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  258.  
  259.     s->level = level;
  260.     s->strategy = strategy;
  261.     s->method = (Byte)method;
  262.  
  263.     return deflateReset(strm);
  264. }
  265.  
  266. /* ========================================================================= */
  267. int deflateSetDictionary (strm, dictionary, dictLength)
  268.     z_stream *strm;
  269.     const Bytef *dictionary;
  270.     uInt  dictLength;
  271. {
  272.     deflate_state *s;
  273.     uInt length = dictLength;
  274.     uInt n;
  275.     IPos hash_head = 0;
  276.  
  277.     if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  278.         strm->state->status != INIT_STATE) return Z_STREAM_ERROR;
  279.  
  280.     s = strm->state;
  281.     strm->adler = adler32(strm->adler, dictionary, dictLength);
  282.  
  283.     if (length < MIN_MATCH) return Z_OK;
  284.     if (length > MAX_DIST(s)) {
  285.     length = MAX_DIST(s);
  286.     dictionary += dictLength - length;
  287.     }
  288.     zmemcpy((charf *)s->window, dictionary, length);
  289.     s->strstart = length;
  290.     s->block_start = (long)length;
  291.  
  292.     /* Insert all strings in the hash table (except for the last two bytes).
  293.      * s->lookahead stays null, so s->ins_h will be recomputed at the next
  294.      * call of fill_window.
  295.      */
  296.     s->ins_h = s->window[0];
  297.     UPDATE_HASH(s, s->ins_h, s->window[1]);
  298.     for (n = 0; n <= length - MIN_MATCH; n++) {
  299.     INSERT_STRING(s, n, hash_head);
  300.     }
  301.     if (hash_head) hash_head = 0;  /* to make compiler happy */
  302.     return Z_OK;
  303. }
  304.  
  305. /* ========================================================================= */
  306. int deflateReset (strm)
  307.     z_stream *strm;
  308. {
  309.     deflate_state *s;
  310.     
  311.     if (strm == Z_NULL || strm->state == Z_NULL ||
  312.         strm->zalloc == Z_NULL || strm->zfree == Z_NULL) return Z_STREAM_ERROR;
  313.  
  314.     strm->total_in = strm->total_out = 0;
  315.     strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  316.     strm->data_type = Z_UNKNOWN;
  317.  
  318.     s = (deflate_state *)strm->state;
  319.     s->pending = 0;
  320.     s->pending_out = s->pending_buf;
  321.  
  322.     if (s->noheader < 0) {
  323.         s->noheader = 0; /* was set to -1 by deflate(..., Z_FINISH); */
  324.     }
  325.     s->status = s->noheader ? BUSY_STATE : INIT_STATE;
  326.     strm->adler = 1;
  327.     s->last_flush = Z_NO_FLUSH;
  328.  
  329.     _tr_init(s);
  330.     lm_init(s);
  331.  
  332.     return Z_OK;
  333. }
  334.  
  335. /* ========================================================================= */
  336. int deflateParams(strm, level, strategy)
  337.     z_stream *strm;
  338.     int level;
  339.     int strategy;
  340. {
  341.     deflate_state *s;
  342.     compress_func func;
  343.     int err = Z_OK;
  344.  
  345.     if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  346.     s = strm->state;
  347.  
  348.     if (level == Z_DEFAULT_COMPRESSION) {
  349.     level = 6;
  350.     }
  351.     if (level < 0 || level > 9 || strategy < 0 || strategy > Z_HUFFMAN_ONLY) {
  352.     return Z_STREAM_ERROR;
  353.     }
  354.     func = configuration_table[s->level].func;
  355.  
  356.     if (func != configuration_table[level].func && strm->total_in != 0) {
  357.     /* Flush the last buffer: */
  358.     err = deflate(strm, Z_PARTIAL_FLUSH);
  359.     }
  360.     if (s->level != level) {
  361.     s->level = level;
  362.     s->max_lazy_match   = configuration_table[level].max_lazy;
  363.     s->good_match       = configuration_table[level].good_length;
  364.     s->nice_match       = configuration_table[level].nice_length;
  365.     s->max_chain_length = configuration_table[level].max_chain;
  366.     }
  367.     s->strategy = strategy;
  368.     return err;
  369. }
  370.  
  371. /* =========================================================================
  372.  * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  373.  * IN assertion: the stream state is correct and there is enough room in
  374.  * pending_buf.
  375.  */
  376. local void putShortMSB (s, b)
  377.     deflate_state *s;
  378.     uInt b;
  379. {
  380.     put_byte(s, (Byte)(b >> 8));
  381.     put_byte(s, (Byte)(b & 0xff));
  382. }   
  383.  
  384. /* =========================================================================
  385.  * Flush as much pending output as possible. All deflate() output goes
  386.  * through this function so some applications may wish to modify it
  387.  * to avoid allocating a large strm->next_out buffer and copying into it.
  388.  * (See also read_buf()).
  389.  */
  390. local void flush_pending(strm)
  391.     z_stream *strm;
  392. {
  393.     unsigned len = strm->state->pending;
  394.  
  395.     if (len > strm->avail_out) len = strm->avail_out;
  396.     if (len == 0) return;
  397.  
  398.     zmemcpy(strm->next_out, strm->state->pending_out, len);
  399.     strm->next_out  += len;
  400.     strm->state->pending_out  += len;
  401.     strm->total_out += len;
  402.     strm->avail_out  -= len;
  403.     strm->state->pending -= len;
  404.     if (strm->state->pending == 0) {
  405.         strm->state->pending_out = strm->state->pending_buf;
  406.     }
  407. }
  408.  
  409. /* ========================================================================= */
  410. int deflate (strm, flush)
  411.     z_stream *strm;
  412.     int flush;
  413. {
  414.     int old_flush; /* value of flush param for previous deflate call */
  415.     deflate_state *s;
  416.  
  417.     if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  418.     
  419.     s = strm->state;
  420.  
  421.     if (strm->next_out == Z_NULL ||
  422.         (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  423.     (s->status == FINISH_STATE && flush != Z_FINISH)) {
  424.         ERR_RETURN(strm, Z_STREAM_ERROR);
  425.     }
  426.     if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  427.  
  428.     s->strm = strm; /* just in case */
  429.     old_flush = s->last_flush;
  430.     s->last_flush = flush;
  431.  
  432.     /* Write the zlib header */
  433.     if (s->status == INIT_STATE) {
  434.  
  435.         uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  436.         uInt level_flags = (s->level-1) >> 1;
  437.  
  438.         if (level_flags > 3) level_flags = 3;
  439.         header |= (level_flags << 6);
  440.     if (s->strstart != 0) header |= PRESET_DICT;
  441.         header += 31 - (header % 31);
  442.  
  443.         s->status = BUSY_STATE;
  444.         putShortMSB(s, header);
  445.  
  446.     /* Save the adler32 of the preset dictionary: */
  447.     if (s->strstart != 0) {
  448.         putShortMSB(s, (uInt)(strm->adler >> 16));
  449.         putShortMSB(s, (uInt)(strm->adler & 0xffff));
  450.         strm->adler = 1L;
  451.     }
  452.     }
  453.  
  454.     /* Flush as much pending output as possible */
  455.     if (s->pending != 0) {
  456.         flush_pending(strm);
  457.         if (strm->avail_out == 0) return Z_OK;
  458.  
  459.     /* Make sure there is something to do and avoid duplicate consecutive
  460.      * flushes. For repeated and useless calls with Z_FINISH, we keep
  461.      * returning Z_STREAM_END instead of Z_BUFF_ERROR.
  462.      */
  463.     } else if (strm->avail_in == 0 && flush <= old_flush &&
  464.            flush != Z_FINISH) {
  465.         ERR_RETURN(strm, Z_BUF_ERROR);
  466.     }
  467.  
  468.     /* User must not provide more input after the first FINISH: */
  469.     if (s->status == FINISH_STATE && strm->avail_in != 0) {
  470.         ERR_RETURN(strm, Z_BUF_ERROR);
  471.     }
  472.  
  473.     /* Start a new block or continue the current one.
  474.      */
  475.     if (strm->avail_in != 0 || s->lookahead != 0 ||
  476.         (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  477.         int quit;
  478.  
  479.         if (flush == Z_FINISH) {
  480.             s->status = FINISH_STATE;
  481.         }
  482.     quit = (*(configuration_table[s->level].func))(s, flush);
  483.  
  484.         if (quit || strm->avail_out == 0) return Z_OK;
  485.         /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  486.          * of deflate should use the same flush parameter to make sure
  487.          * that the flush is complete. So we don't have to output an
  488.          * empty block here, this will be done at next call. This also
  489.          * ensures that for a very small output buffer, we emit at most
  490.          * one empty block.
  491.          */
  492.         if (flush != Z_NO_FLUSH && flush != Z_FINISH) {
  493.             if (flush == Z_PARTIAL_FLUSH) {
  494.                 _tr_align(s);
  495.             } else { /* FULL_FLUSH or SYNC_FLUSH */
  496.                 _tr_stored_block(s, (char*)0, 0L, 0);
  497.                 /* For a full flush, this empty block will be recognized
  498.                  * as a special marker by inflate_sync().
  499.                  */
  500.                 if (flush == Z_FULL_FLUSH) {
  501.                     CLEAR_HASH(s);             /* forget history */
  502.                 }
  503.             }
  504.             flush_pending(strm);
  505.             if (strm->avail_out == 0) return Z_OK;
  506.         }
  507.     }
  508.     Assert(strm->avail_out > 0, "bug2");
  509.  
  510.     if (flush != Z_FINISH) return Z_OK;
  511.     if (s->noheader) return Z_STREAM_END;
  512.  
  513.     /* Write the zlib trailer (adler32) */
  514.     putShortMSB(s, (uInt)(strm->adler >> 16));
  515.     putShortMSB(s, (uInt)(strm->adler & 0xffff));
  516.     flush_pending(strm);
  517.     /* If avail_out is zero, the application will call deflate again
  518.      * to flush the rest.
  519.      */
  520.     s->noheader = -1; /* write the trailer only once! */
  521.     return s->pending != 0 ? Z_OK : Z_STREAM_END;
  522. }
  523.  
  524. /* ========================================================================= */
  525. int deflateEnd (strm)
  526.     z_stream *strm;
  527. {
  528.     int status;
  529.  
  530.     if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  531.  
  532.     /* Deallocate in reverse order of allocations: */
  533.     TRY_FREE(strm, strm->state->pending_buf);
  534.     TRY_FREE(strm, strm->state->head);
  535.     TRY_FREE(strm, strm->state->prev);
  536.     TRY_FREE(strm, strm->state->window);
  537.  
  538.     status = strm->state->status;
  539.     ZFREE(strm, strm->state);
  540.     strm->state = Z_NULL;
  541.  
  542.     return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  543. }
  544.  
  545. /* ========================================================================= */
  546. int deflateCopy (dest, source)
  547.     z_stream *dest;
  548.     z_stream *source;
  549. {
  550.     if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  551.         return Z_STREAM_ERROR;
  552.     }
  553.     *dest = *source;
  554.     return Z_STREAM_ERROR; /* to be implemented */
  555. #if 0
  556.     dest->state = (struct internal_state FAR *)
  557.         (*dest->zalloc)(1, sizeof(deflate_state));
  558.     if (dest->state == Z_NULL) return Z_MEM_ERROR;
  559.  
  560.     *(dest->state) = *(source->state);
  561.     return Z_OK;
  562. #endif
  563. }
  564.  
  565. /* ===========================================================================
  566.  * Read a new buffer from the current input stream, update the adler32
  567.  * and total number of bytes read.  All deflate() input goes through
  568.  * this function so some applications may wish to modify it to avoid
  569.  * allocating a large strm->next_in buffer and copying from it.
  570.  * (See also flush_pending()).
  571.  */
  572. local int read_buf(strm, buf, size)
  573.     z_stream *strm;
  574.     charf *buf;
  575.     unsigned size;
  576. {
  577.     unsigned len = strm->avail_in;
  578.  
  579.     if (len > size) len = size;
  580.     if (len == 0) return 0;
  581.  
  582.     strm->avail_in  -= len;
  583.  
  584.     if (!strm->state->noheader) {
  585.         strm->adler = adler32(strm->adler, strm->next_in, len);
  586.     }
  587.     zmemcpy(buf, strm->next_in, len);
  588.     strm->next_in  += len;
  589.     strm->total_in += len;
  590.  
  591.     return (int)len;
  592. }
  593.  
  594. /* ===========================================================================
  595.  * Initialize the "longest match" routines for a new zlib stream
  596.  */
  597. local void lm_init (s)
  598.     deflate_state *s;
  599. {
  600.     s->window_size = (ulg)2L*s->w_size;
  601.  
  602.     CLEAR_HASH(s);
  603.  
  604.     /* Set the default configuration parameters:
  605.      */
  606.     s->max_lazy_match   = configuration_table[s->level].max_lazy;
  607.     s->good_match       = configuration_table[s->level].good_length;
  608.     s->nice_match       = configuration_table[s->level].nice_length;
  609.     s->max_chain_length = configuration_table[s->level].max_chain;
  610.  
  611.     s->strstart = 0;
  612.     s->block_start = 0L;
  613.     s->lookahead = 0;
  614.     s->match_length = s->prev_length = MIN_MATCH-1;
  615.     s->match_available = 0;
  616.     s->ins_h = 0;
  617. #ifdef ASMV
  618.     match_init(); /* initialize the asm code */
  619. #endif
  620. }
  621.  
  622. /* ===========================================================================
  623.  * Set match_start to the longest match starting at the given string and
  624.  * return its length. Matches shorter or equal to prev_length are discarded,
  625.  * in which case the result is equal to prev_length and match_start is
  626.  * garbage.
  627.  * IN assertions: cur_match is the head of the hash chain for the current
  628.  *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  629.  * OUT assertion: the match length is not greater than s->lookahead.
  630.  */
  631. #ifndef ASMV
  632. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  633.  * match.S. The code will be functionally equivalent.
  634.  */
  635. local uInt longest_match(s, cur_match)
  636.     deflate_state *s;
  637.     IPos cur_match;                             /* current match */
  638. {
  639.     unsigned chain_length = s->max_chain_length;/* max hash chain length */
  640.     register Bytef *scan = s->window + s->strstart; /* current string */
  641.     register Bytef *match;                       /* matched string */
  642.     register int len;                           /* length of current match */
  643.     int best_len = s->prev_length;              /* best match length so far */
  644.     int nice_match = s->nice_match;             /* stop if match long enough */
  645.     IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  646.         s->strstart - (IPos)MAX_DIST(s) : NIL;
  647.     /* Stop when cur_match becomes <= limit. To simplify the code,
  648.      * we prevent matches with the string of window index 0.
  649.      */
  650.     Posf *prev = s->prev;
  651.     uInt wmask = s->w_mask;
  652.  
  653. #ifdef UNALIGNED_OK
  654.     /* Compare two bytes at a time. Note: this is not always beneficial.
  655.      * Try with and without -DUNALIGNED_OK to check.
  656.      */
  657.     register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  658.     register ush scan_start = *(ushf*)scan;
  659.     register ush scan_end   = *(ushf*)(scan+best_len-1);
  660. #else
  661.     register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  662.     register Byte scan_end1  = scan[best_len-1];
  663.     register Byte scan_end   = scan[best_len];
  664. #endif
  665.  
  666.     /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  667.      * It is easy to get rid of this optimization if necessary.
  668.      */
  669.     Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  670.  
  671.     /* Do not waste too much time if we already have a good match: */
  672.     if (s->prev_length >= s->good_match) {
  673.         chain_length >>= 2;
  674.     }
  675.     /* Do not look for matches beyond the end of the input. This is necessary
  676.      * to make deflate deterministic.
  677.      */
  678.     if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  679.  
  680.     Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  681.  
  682.     do {
  683.         Assert(cur_match < s->strstart, "no future");
  684.         match = s->window + cur_match;
  685.  
  686.         /* Skip to next match if the match length cannot increase
  687.          * or if the match length is less than 2:
  688.          */
  689. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  690.         /* This code assumes sizeof(unsigned short) == 2. Do not use
  691.          * UNALIGNED_OK if your compiler uses a different size.
  692.          */
  693.         if (*(ushf*)(match+best_len-1) != scan_end ||
  694.             *(ushf*)match != scan_start) continue;
  695.  
  696.         /* It is not necessary to compare scan[2] and match[2] since they are
  697.          * always equal when the other bytes match, given that the hash keys
  698.          * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  699.          * strstart+3, +5, ... up to strstart+257. We check for insufficient
  700.          * lookahead only every 4th comparison; the 128th check will be made
  701.          * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  702.          * necessary to put more guard bytes at the end of the window, or
  703.          * to check more often for insufficient lookahead.
  704.          */
  705.         Assert(scan[2] == match[2], "scan[2]?");
  706.         scan++, match++;
  707.         do {
  708.         } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  709.                  *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  710.                  *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  711.                  *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  712.                  scan < strend);
  713.         /* The funny "do {}" generates better code on most compilers */
  714.  
  715.         /* Here, scan <= window+strstart+257 */
  716.         Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  717.         if (*scan == *match) scan++;
  718.  
  719.         len = (MAX_MATCH - 1) - (int)(strend-scan);
  720.         scan = strend - (MAX_MATCH-1);
  721.  
  722. #else /* UNALIGNED_OK */
  723.  
  724.         if (match[best_len]   != scan_end  ||
  725.             match[best_len-1] != scan_end1 ||
  726.             *match            != *scan     ||
  727.             *++match          != scan[1])      continue;
  728.  
  729.         /* The check at best_len-1 can be removed because it will be made
  730.          * again later. (This heuristic is not always a win.)
  731.          * It is not necessary to compare scan[2] and match[2] since they
  732.          * are always equal when the other bytes match, given that
  733.          * the hash keys are equal and that HASH_BITS >= 8.
  734.          */
  735.         scan += 2, match++;
  736.         Assert(*scan == *match, "match[2]?");
  737.  
  738.         /* We check for insufficient lookahead only every 8th comparison;
  739.          * the 256th check will be made at strstart+258.
  740.          */
  741.         do {
  742.         } while (*++scan == *++match && *++scan == *++match &&
  743.                  *++scan == *++match && *++scan == *++match &&
  744.                  *++scan == *++match && *++scan == *++match &&
  745.                  *++scan == *++match && *++scan == *++match &&
  746.                  scan < strend);
  747.  
  748.         Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  749.  
  750.         len = MAX_MATCH - (int)(strend - scan);
  751.         scan = strend - MAX_MATCH;
  752.  
  753. #endif /* UNALIGNED_OK */
  754.  
  755.         if (len > best_len) {
  756.             s->match_start = cur_match;
  757.             best_len = len;
  758.             if (len >= nice_match) break;
  759. #ifdef UNALIGNED_OK
  760.             scan_end = *(ushf*)(scan+best_len-1);
  761. #else
  762.             scan_end1  = scan[best_len-1];
  763.             scan_end   = scan[best_len];
  764. #endif
  765.         }
  766.     } while ((cur_match = prev[cur_match & wmask]) > limit
  767.              && --chain_length != 0);
  768.  
  769.     if ((uInt)best_len <= s->lookahead) return best_len;
  770.     return s->lookahead;
  771. }
  772. #endif /* ASMV */
  773.  
  774. #ifdef DEBUG
  775. /* ===========================================================================
  776.  * Check that the match at match_start is indeed a match.
  777.  */
  778. local void check_match(s, start, match, length)
  779.     deflate_state *s;
  780.     IPos start, match;
  781.     int length;
  782. {
  783.     /* check that the match is indeed a match */
  784.     if (zmemcmp((charf *)s->window + match,
  785.                 (charf *)s->window + start, length) != EQUAL) {
  786.         fprintf(stderr, " start %u, match %u, length %d\n",
  787.         start, match, length);
  788.         do {
  789.         fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  790.     } while (--length != 0);
  791.         z_error("invalid match");
  792.     }
  793.     if (verbose > 1) {
  794.         fprintf(stderr,"\\[%d,%d]", start-match, length);
  795.         do { putc(s->window[start++], stderr); } while (--length != 0);
  796.     }
  797. }
  798. #else
  799. #  define check_match(s, start, match, length)
  800. #endif
  801.  
  802. /* ===========================================================================
  803.  * Fill the window when the lookahead becomes insufficient.
  804.  * Updates strstart and lookahead.
  805.  *
  806.  * IN assertion: lookahead < MIN_LOOKAHEAD
  807.  * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  808.  *    At least one byte has been read, or avail_in == 0; reads are
  809.  *    performed for at least two bytes (required for the zip translate_eol
  810.  *    option -- not supported here).
  811.  */
  812. local void fill_window(s)
  813.     deflate_state *s;
  814. {
  815.     register unsigned n, m;
  816.     register Posf *p;
  817.     unsigned more;    /* Amount of free space at the end of the window. */
  818.     uInt wsize = s->w_size;
  819.  
  820.     do {
  821.         more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  822.  
  823.         /* Deal with !@#$% 64K limit: */
  824.         if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  825.             more = wsize;
  826.  
  827.         } else if (more == (unsigned)(-1)) {
  828.             /* Very unlikely, but possible on 16 bit machine if strstart == 0
  829.              * and lookahead == 1 (input done one byte at time)
  830.              */
  831.             more--;
  832.  
  833.         /* If the window is almost full and there is insufficient lookahead,
  834.          * move the upper half to the lower one to make room in the upper half.
  835.          */
  836.         } else if (s->strstart >= wsize+MAX_DIST(s)) {
  837.  
  838.             zmemcpy((charf *)s->window, (charf *)s->window+wsize,
  839.                    (unsigned)wsize);
  840.             s->match_start -= wsize;
  841.             s->strstart    -= wsize; /* we now have strstart >= MAX_DIST */
  842.  
  843.             s->block_start -= (long) wsize;
  844.  
  845.             /* Slide the hash table (could be avoided with 32 bit values
  846.                at the expense of memory usage):
  847.              */
  848.             n = s->hash_size;
  849.             p = &s->head[n];
  850.             do {
  851.                 m = *--p;
  852.                 *p = (Pos)(m >= wsize ? m-wsize : NIL);
  853.             } while (--n);
  854.  
  855.             n = wsize;
  856.             p = &s->prev[n];
  857.             do {
  858.                 m = *--p;
  859.                 *p = (Pos)(m >= wsize ? m-wsize : NIL);
  860.                 /* If n is not on any hash chain, prev[n] is garbage but
  861.                  * its value will never be used.
  862.                  */
  863.             } while (--n);
  864.  
  865.             more += wsize;
  866.         }
  867.         if (s->strm->avail_in == 0) return;
  868.  
  869.         /* If there was no sliding:
  870.          *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  871.          *    more == window_size - lookahead - strstart
  872.          * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  873.          * => more >= window_size - 2*WSIZE + 2
  874.          * In the BIG_MEM or MMAP case (not yet supported),
  875.          *   window_size == input_size + MIN_LOOKAHEAD  &&
  876.          *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  877.          * Otherwise, window_size == 2*WSIZE so more >= 2.
  878.          * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  879.          */
  880.         Assert(more >= 2, "more < 2");
  881.  
  882.         n = read_buf(s->strm, (charf *)s->window + s->strstart + s->lookahead,
  883.                      more);
  884.         s->lookahead += n;
  885.  
  886.         /* Initialize the hash value now that we have some input: */
  887.         if (s->lookahead >= MIN_MATCH) {
  888.             s->ins_h = s->window[s->strstart];
  889.             UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  890. #if MIN_MATCH != 3
  891.             Call UPDATE_HASH() MIN_MATCH-3 more times
  892. #endif
  893.         }
  894.         /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  895.          * but this is not important since only literal bytes will be emitted.
  896.          */
  897.  
  898.     } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  899. }
  900.  
  901. /* ===========================================================================
  902.  * Flush the current block, with given end-of-file flag.
  903.  * IN assertion: strstart is set to the end of the current match.
  904.  */
  905. #define FLUSH_BLOCK_ONLY(s, eof) { \
  906.    _tr_flush_block(s, (s->block_start >= 0L ? \
  907.                    (charf *)&s->window[(unsigned)s->block_start] : \
  908.                    (charf *)Z_NULL), \
  909.         (ulg)((long)s->strstart - s->block_start), \
  910.         (eof)); \
  911.    s->block_start = s->strstart; \
  912.    flush_pending(s->strm); \
  913.    Tracev((stderr,"[FLUSH]")); \
  914. }
  915.  
  916. /* Same but force premature exit if necessary. */
  917. #define FLUSH_BLOCK(s, eof) { \
  918.    FLUSH_BLOCK_ONLY(s, eof); \
  919.    if (s->strm->avail_out == 0) return 1; \
  920. }
  921.  
  922. /* ===========================================================================
  923.  * Copy without compression as much as possible from the input stream, return
  924.  * true if processing was terminated prematurely (no more input or output
  925.  * space).  This function does not insert new strings in the dictionary
  926.  * since uncompressible data is probably not useful. This function is used
  927.  * only for the level=0 compression option.
  928.  * NOTE: this function should be optimized to avoid extra copying.
  929.  */
  930. local int deflate_stored(s, flush)
  931.     deflate_state *s;
  932.     int flush;
  933. {
  934.     for (;;) {
  935.         /* Fill the window as much as possible: */
  936.         if (s->lookahead <= 1) {
  937.  
  938.             Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  939.            s->block_start >= (long)s->w_size, "slide too late");
  940.  
  941.             fill_window(s);
  942.             if (s->lookahead == 0 && flush == Z_NO_FLUSH) return 1;
  943.  
  944.             if (s->lookahead == 0) break; /* flush the current block */
  945.         }
  946.     Assert(s->block_start >= 0L, "block gone");
  947.  
  948.     s->strstart += s->lookahead;
  949.     s->lookahead = 0;
  950.  
  951.         /* Stored blocks are limited to 0xffff bytes: */
  952.         if (s->strstart == 0 || s->strstart > 0xfffe) {
  953.         /* strstart == 0 is possible when wraparound on 16-bit machine */
  954.         s->lookahead = s->strstart - 0xffff;
  955.         s->strstart = 0xffff;
  956.     }
  957.  
  958.     /* Emit a stored block if it is large enough: */
  959.         if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  960.             FLUSH_BLOCK(s, 0);
  961.     }
  962.     }
  963.     FLUSH_BLOCK(s, flush == Z_FINISH);
  964.     return 0; /* normal exit */
  965. }
  966.  
  967. /* ===========================================================================
  968.  * Compress as much as possible from the input stream, return true if
  969.  * processing was terminated prematurely (no more input or output space).
  970.  * This function does not perform lazy evaluation of matches and inserts
  971.  * new strings in the dictionary only for unmatched strings or for short
  972.  * matches. It is used only for the fast compression options.
  973.  */
  974. local int deflate_fast(s, flush)
  975.     deflate_state *s;
  976.     int flush;
  977. {
  978.     IPos hash_head = NIL; /* head of the hash chain */
  979.     int bflush;           /* set if current block must be flushed */
  980.  
  981.     for (;;) {
  982.         /* Make sure that we always have enough lookahead, except
  983.          * at the end of the input file. We need MAX_MATCH bytes
  984.          * for the next match, plus MIN_MATCH bytes to insert the
  985.          * string following the next match.
  986.          */
  987.         if (s->lookahead < MIN_LOOKAHEAD) {
  988.             fill_window(s);
  989.             if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) return 1;
  990.  
  991.             if (s->lookahead == 0) break; /* flush the current block */
  992.         }
  993.  
  994.         /* Insert the string window[strstart .. strstart+2] in the
  995.          * dictionary, and set hash_head to the head of the hash chain:
  996.          */
  997.         if (s->lookahead >= MIN_MATCH) {
  998.             INSERT_STRING(s, s->strstart, hash_head);
  999.         }
  1000.  
  1001.         /* Find the longest match, discarding those <= prev_length.
  1002.          * At this point we have always match_length < MIN_MATCH
  1003.          */
  1004.         if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  1005.             /* To simplify the code, we prevent matches with the string
  1006.              * of window index 0 (in particular we have to avoid a match
  1007.              * of the string with itself at the start of the input file).
  1008.              */
  1009.             if (s->strategy != Z_HUFFMAN_ONLY) {
  1010.                 s->match_length = longest_match (s, hash_head);
  1011.             }
  1012.             /* longest_match() sets match_start */
  1013.         }
  1014.         if (s->match_length >= MIN_MATCH) {
  1015.             check_match(s, s->strstart, s->match_start, s->match_length);
  1016.  
  1017.             bflush = _tr_tally(s, s->strstart - s->match_start,
  1018.                                s->match_length - MIN_MATCH);
  1019.  
  1020.             s->lookahead -= s->match_length;
  1021.  
  1022.             /* Insert new strings in the hash table only if the match length
  1023.              * is not too large. This saves time but degrades compression.
  1024.              */
  1025.             if (s->match_length <= s->max_insert_length &&
  1026.                 s->lookahead >= MIN_MATCH) {
  1027.                 s->match_length--; /* string at strstart already in hash table */
  1028.                 do {
  1029.                     s->strstart++;
  1030.                     INSERT_STRING(s, s->strstart, hash_head);
  1031.                     /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  1032.                      * always MIN_MATCH bytes ahead.
  1033.                      */
  1034.                 } while (--s->match_length != 0);
  1035.                 s->strstart++; 
  1036.             } else {
  1037.                 s->strstart += s->match_length;
  1038.                 s->match_length = 0;
  1039.                 s->ins_h = s->window[s->strstart];
  1040.                 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  1041. #if MIN_MATCH != 3
  1042.                 Call UPDATE_HASH() MIN_MATCH-3 more times
  1043. #endif
  1044.                 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  1045.                  * matter since it will be recomputed at next deflate call.
  1046.                  */
  1047.             }
  1048.         } else {
  1049.             /* No match, output a literal byte */
  1050.             Tracevv((stderr,"%c", s->window[s->strstart]));
  1051.             bflush = _tr_tally (s, 0, s->window[s->strstart]);
  1052.             s->lookahead--;
  1053.             s->strstart++; 
  1054.         }
  1055.         if (bflush) FLUSH_BLOCK(s, 0);
  1056.     }
  1057.     FLUSH_BLOCK(s, flush == Z_FINISH);
  1058.     return 0; /* normal exit */
  1059. }
  1060.  
  1061. /* ===========================================================================
  1062.  * Same as above, but achieves better compression. We use a lazy
  1063.  * evaluation for matches: a match is finally adopted only if there is
  1064.  * no better match at the next window position.
  1065.  */
  1066. local int deflate_slow(s, flush)
  1067.     deflate_state *s;
  1068.     int flush;
  1069. {
  1070.     IPos hash_head = NIL;    /* head of hash chain */
  1071.     int bflush;              /* set if current block must be flushed */
  1072.  
  1073.     /* Process the input block. */
  1074.     for (;;) {
  1075.         /* Make sure that we always have enough lookahead, except
  1076.          * at the end of the input file. We need MAX_MATCH bytes
  1077.          * for the next match, plus MIN_MATCH bytes to insert the
  1078.          * string following the next match.
  1079.          */
  1080.         if (s->lookahead < MIN_LOOKAHEAD) {
  1081.             fill_window(s);
  1082.             if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) return 1;
  1083.  
  1084.             if (s->lookahead == 0) break; /* flush the current block */
  1085.         }
  1086.  
  1087.         /* Insert the string window[strstart .. strstart+2] in the
  1088.          * dictionary, and set hash_head to the head of the hash chain:
  1089.          */
  1090.         if (s->lookahead >= MIN_MATCH) {
  1091.             INSERT_STRING(s, s->strstart, hash_head);
  1092.         }
  1093.  
  1094.         /* Find the longest match, discarding those <= prev_length.
  1095.          */
  1096.         s->prev_length = s->match_length, s->prev_match = s->match_start;
  1097.         s->match_length = MIN_MATCH-1;
  1098.  
  1099.         if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  1100.             s->strstart - hash_head <= MAX_DIST(s)) {
  1101.             /* To simplify the code, we prevent matches with the string
  1102.              * of window index 0 (in particular we have to avoid a match
  1103.              * of the string with itself at the start of the input file).
  1104.              */
  1105.             if (s->strategy != Z_HUFFMAN_ONLY) {
  1106.                 s->match_length = longest_match (s, hash_head);
  1107.             }
  1108.             /* longest_match() sets match_start */
  1109.  
  1110.             if (s->match_length <= 5 && (s->strategy == Z_FILTERED ||
  1111.                  (s->match_length == MIN_MATCH &&
  1112.                   s->strstart - s->match_start > TOO_FAR))) {
  1113.  
  1114.                 /* If prev_match is also MIN_MATCH, match_start is garbage
  1115.                  * but we will ignore the current match anyway.
  1116.                  */
  1117.                 s->match_length = MIN_MATCH-1;
  1118.             }
  1119.         }
  1120.         /* If there was a match at the previous step and the current
  1121.          * match is not better, output the previous match:
  1122.          */
  1123.         if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  1124.             uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  1125.             /* Do not insert strings in hash table beyond this. */
  1126.  
  1127.             check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  1128.  
  1129.             bflush = _tr_tally(s, s->strstart -1 - s->prev_match,
  1130.                                s->prev_length - MIN_MATCH);
  1131.  
  1132.             /* Insert in hash table all strings up to the end of the match.
  1133.              * strstart-1 and strstart are already inserted. If there is not
  1134.              * enough lookahead, the last two strings are not inserted in
  1135.              * the hash table.
  1136.              */
  1137.             s->lookahead -= s->prev_length-1;
  1138.             s->prev_length -= 2;
  1139.             do {
  1140.                 if (++s->strstart <= max_insert) {
  1141.                     INSERT_STRING(s, s->strstart, hash_head);
  1142.                 }
  1143.             } while (--s->prev_length != 0);
  1144.             s->match_available = 0;
  1145.             s->match_length = MIN_MATCH-1;
  1146.             s->strstart++;
  1147.  
  1148.             if (bflush) FLUSH_BLOCK(s, 0);
  1149.  
  1150.         } else if (s->match_available) {
  1151.             /* If there was no match at the previous position, output a
  1152.              * single literal. If there was a match but the current match
  1153.              * is longer, truncate the previous match to a single literal.
  1154.              */
  1155.             Tracevv((stderr,"%c", s->window[s->strstart-1]));
  1156.             if (_tr_tally (s, 0, s->window[s->strstart-1])) {
  1157.                 FLUSH_BLOCK_ONLY(s, 0);
  1158.             }
  1159.             s->strstart++;
  1160.             s->lookahead--;
  1161.             if (s->strm->avail_out == 0) return 1;
  1162.         } else {
  1163.             /* There is no previous match to compare with, wait for
  1164.              * the next step to decide.
  1165.              */
  1166.             s->match_available = 1;
  1167.             s->strstart++;
  1168.             s->lookahead--;
  1169.         }
  1170.     }
  1171.     Assert (flush != Z_NO_FLUSH, "no flush?");
  1172.     if (s->match_available) {
  1173.         Tracevv((stderr,"%c", s->window[s->strstart-1]));
  1174.         _tr_tally (s, 0, s->window[s->strstart-1]);
  1175.         s->match_available = 0;
  1176.     }
  1177.     FLUSH_BLOCK(s, flush == Z_FINISH);
  1178.     return 0;
  1179. }
  1180.  
  1181.